#include "cgzCTimer.h"
#include "cgzCThreadPool.h"
#include "cgzAFun.h"

tagTimer::tagTimer(int64_t coockid, int64_t expiration)
    : m_cookid(coockid),
      m_expiration(expiration + fnowmls())
{
}

tagTimer::~tagTimer()
{
}

bool tagTimer::operator>(const tagTimer *other) const
{
    return m_expiration > other->m_expiration;
}

cgzCTimer::cgzCTimer(cgzCThreadPool *pool, const char *name)
    : cgzITask(pool, name, cgzETask::CTimer)
{
}

cgzCTimer::~cgzCTimer()
{
}

bool cgzCTimer::run(int64_t nms)
{
    // 检测添加定时器
    while (!m_runTask.empty())
    {
        auto ptask = m_runTask.front();
        m_runTask.pop_front();
        m_timers.push(static_cast<tagTimer *>(ptask));
    }

    bool has = false;
    int min = 100;
    while (!m_timers.empty())
    {
        // 检测定时器触发
        auto top = m_timers.top();
        m_timers.pop();
        int diff = top->m_expiration - nms;
        min = std::min(min, diff);
        if (diff > 0)
        {
            // 没有到触发时间
            if (!has)
            {
                // 下次检查
                has = true;
                todoret(top);
            }
            break;
        }
        else
        {
            // 返回主线程
            has = true;
            ret(top);
        }
    }

    min = std::max(min, 1);
    m_runms = nms + min;
    return true;
}

bool cgzCTimer::todoret(tagTimer *cgzTask)
{
    // 返给自己
    m_retTask.push_back(cgzTask);
    return true;
}

bool cgzCTimer::ret(tagTimer *cgzTask)
{
    // 返回主线程
    bool ret = cgzITask::retTask(cgzTask);
    cgzTask->target = cgzTask->origin;
    cgzTask->origin = getId();
    return ret;
}